package nepomuk.sandbox;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osgi.framework.BundleContext;

public class TestServlet extends HttpServlet {

    private final BundleContext fContext;

    public TestServlet(BundleContext context) {
        fContext = context;
    }

    private void copy(InputStream input, OutputStream out) throws IOException {
        byte[] buf = new byte[1024 * 10];
        int len;
        while ((len = input.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    }

    /**
     * @param path
     * @return
     */
    private URL getBundleEntry(String path) {
        return fContext.getBundle().getEntry(path);
    }

    private String readData() throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            URL data = getBundleEntry("/data/rpm.rdf");
            InputStream input = data.openStream();
            try {
                copy(input, out);
            } finally {
                input.close();
            }
        } finally {
            out.close();
        }
        return new String(out.toByteArray(), "UTF-8");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException,
        IOException {
        String path = req.getPathInfo();
        ServletOutputStream out = resp.getOutputStream();
        if (path.startsWith("/resources")) {
            path = path.substring("/resources".length());
            URL url = getBundleEntry(path);
            if (url == null)
                resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            else {
                InputStream input = url.openStream();
                try {
                    copy(input, out);
                } finally {
                    input.close();
                }
            }
        } else {
            String prefix = req.getContextPath();
            if (prefix == null || "".equals(prefix))
                prefix = "/";
            out.println("<?xml version='1.0' encoding='UTF-8'?>\n"
                + "<?xml-stylesheet type='text/xsl' href='"
                + prefix
                + "resources/.xsl/view.xsl'?>\n");

            String content = readData();
            out.println(content);
        }
    }
}
